package com.cmhi.softmbh.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.cmhi.softmbh.MyApplication;
import com.softmbh.kellyplatform.util.AppUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

public class HardwareUtil {

//    /**
//     * @return MAC 地址
//     */
//    public static String getMacAddress() {
//        FileReader fr = null;
//        BufferedReader br = null;
//        String path = "/sys/class/net/eth0/address";
//        String readLine;
//        String mac = "";
//        try {
//            fr = new FileReader(path);
//            br = new BufferedReader(fr, 8192);
//            while ((readLine = br.readLine()) != null) {
//                mac = readLine;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (br != null) {
//                    br.close();
//                }
//                if (fr != null) {
//                    fr.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        if (!mac.isEmpty()) {
//            return mac.replace(":", "").toUpperCase();
//        } else {
//            return GetWifiMacAddress.getWifiMacAddress();
//        }
//    }

    /**
     * 获取 mac 地址
     * 小荷音响厂家提供方法
     *
     * @return mac 地址
     */
    public static String xiaoHeGetMac() {
        String macAddress;
        StringBuilder buf = new StringBuilder();
        NetworkInterface networkInterface;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02x:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        AppUtils.debugLog(macAddress);
        return macAddress.replace(":", "").toUpperCase();
        //return "50:72:0D:39:01:4E";
    }

    /**
     * 便携电视厂家提供方法
     *
     * @return wifi mac 地址，带冒号
     */
    public static String portableTvGetMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString().replace(":", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * @return CPU 型号
     */
    public static String getCpuModel() {
        String cpuHardware = getCpuHardware();
        if (TextUtils.isEmpty(cpuHardware)) {
            cpuHardware = getSystemHardware();
        }
        return cpuHardware;
    }

    public static String getCpuHardware() {
        try {
            String str = "";
            String[] arrayOfString;
            StringBuilder cpuModel = new StringBuilder();
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr, 8192);
            String readLine;
            while ((readLine = br.readLine()) != null) {
                if (readLine.startsWith("Hardware")) {
                    str = readLine;
                }
            }
            arrayOfString = str.split("\\s+");
            if (arrayOfString.length > 0) {
                for (int i = 2; i < arrayOfString.length; i++) {
                    cpuModel.append(arrayOfString[i]).append(" ");
                }
            }
            br.close();
            return cpuModel.toString().trim();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     *
     *
     * @return
     */
    public static String getSystemHardware() {
        Method systemProperties_get = null;
        String ver = null;
        try {
            systemProperties_get = Class.forName("android.os.SystemProperties").getMethod("get", String.class);
            ver = (String) systemProperties_get.invoke(null, "ro.boot.hardware");
            AppUtils.debugLog(("getSystemHardware :ver = " + ver));
        } catch (Exception e) {
            AppUtils.debugLog(("getSystemHardware : " + e.getMessage()));
        }
        return ver;
    }

    /**
     * @return CPU 核心数
     */
    public static int getCpuCoreNumber() {
        //Private Class to display only CPU devices in the directory listing
        try {
            //Get directory containing CPU info
            File file = new File("/sys/devices/system/cpu/");
            //Filter to only list the devices we care about
            File[] files = file.listFiles(new CpuFilter());
            //Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            e.printStackTrace();
            //Default to return 1 core
            return 1;//至少 1 核
        }
    }

    static class CpuFilter implements FileFilter {
        @Override
        public boolean accept(File pathname) {
            //Check if filename is "cpu", followed by a single digit number
            return Pattern.matches("cpu[0-9]", pathname.getName());
        }
    }

    /**
     * @return CPU 频率，单位 GHz
     */
    public static String getCpuFrequencyStr() {
        return new DecimalFormat("0.00").format((float) getCpuFrequencyInt() / (1024 * 1024));
    }

    /**
     * @return CPU 频率，单位 KHz
     */
    public static int getCpuFrequencyInt() {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
            br = new BufferedReader(fr);
            String readLine = br.readLine();
            if (readLine != null) {
                return Integer.parseInt(readLine.trim());
            } else {
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @return 总存储大小，固定单位：MB
     */
    public static String getTotalRom() {
        StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
        return statFs.getTotalBytes() / 1024L / 1024L + "";
    }

    /**
     * @return 可用存储大小，固定单位：MB
     */
    public static String getAvailableRom() {
        StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
        return statFs.getAvailableBytes() / 1024L / 1024L + "";
    }

    /**
     * @return 总存储大小
     */
//    public static String getTotalRomStr() {
//        return Formatter.formatFileSize(MyApplication.myApplication, getTotalRomLong());
//    }
    public static String getTotalRomStr() {
        return bytes2kb(getTotalRomLong());
//        return Formatter.formatFileSize(MyApplication.myApplication, getTotalRomLong());
    }

    /**
     * @return 可用存储大小
     */
//    public static String getAvailableRomStr() {
//        return Formatter.formatFileSize(MyApplication.myApplication, getAvailableRomLong());
//    }
    public static String getAvailableRomStr() {
        return bytes2kb(getAvailableRomLong());
    }

    /**
     * @return 总存储大小，单位 B
     */
    public static long getTotalRomLong() {
        return getRomLong(true);
    }

    /**
     * @return 可用存储大小，单位 B
     */
    public static long getAvailableRomLong() {
        return getRomLong(false);
    }

    /**
     * @param total true: 总存储，false: 可用存储
     * @return 存储大小，单位 B
     */
    @SuppressWarnings("deprecation")
    public static long getRomLong(boolean total) {
        try {
            StatFs stat;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
            } else {
                stat = new StatFs("/data");
            }
            long blockSize = stat.getBlockSize();
            long blocks;
            if (total) {
                blocks = stat.getBlockCount();
            } else {
                blocks = stat.getAvailableBlocks();
            }
            return blockSize * blocks;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * @return 可用内存
     */
//    public static String getAvailableMemoryStr() {
//        return Formatter.formatFileSize(MyApplication.myApplication, getAvailableMemoryLong());
//    }
    public static String getAvailableMemoryStr() {
        return bytes2kb(getAvailableMemoryLong());
    }

    /**
     * @return 可用内存，单位 B
     */
    public static long getAvailableMemoryLong() {
        try {
            ActivityManager am = (ActivityManager) MyApplication.myApplication.getSystemService(Context.ACTIVITY_SERVICE);
            ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
            am.getMemoryInfo(mi);
            return mi.availMem;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * @return 总内存，单位 MB
     */
    public static double getTotalMemory() {
        String readLine;
        String[] arrayOfString;
        long totalMemory;
        try {
            FileReader fr = new FileReader("/proc/meminfo");//系统内存信息文件
            BufferedReader br = new BufferedReader(fr, 8192);
            readLine = br.readLine();//读取 meminfo 第一行，系统总内存大小
            arrayOfString = readLine.split("\\s+");
            totalMemory = Long.parseLong(arrayOfString[1]);
            br.close();
            return Math.ceil((float) (totalMemory / 1024.0));
        } catch (IOException e) {
            e.printStackTrace();
            return 0.0d;
        }
    }

    /**
     * @return IP 地址
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface ni = en.nextElement();
                for (Enumeration<InetAddress> en1 = ni.getInetAddresses(); en1.hasMoreElements(); ) {
                    InetAddress inetAddress = en1.nextElement();
                    AppUtils.debugLog(inetAddress.getHostAddress());
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {

                        AppUtils.debugLog("if:   "+inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }

    public static void showSoftKeyBoard(EditText editText, Activity activity) {
        InputMethodManager mInputMtdManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (mInputMtdManager != null && activity != null) {
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            mInputMtdManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    }

    //定义GB的计算常量
    private static final int GB = 1024 * 1024 * 1024;
    //定义MB的计算常量
    private static final int MB = 1024 * 1024;
    //定义KB的计算常量
    private static final int KB = 1024;

    public static String bytes2kb(long bytes) {
        //格式化小数
        DecimalFormat format = new DecimalFormat("###.0");
        if (bytes / GB >= 1) {
            return format.format(bytes / GB) + "GB";
        } else if (bytes / MB >= 1) {
            return format.format(bytes / MB) + "MB";
        } else if (bytes / KB >= 1) {
            return format.format(bytes / KB) + "KB";
        } else {
            return bytes + "B";
        }
    }

    //给手机号加*
    public static String Phone(String aa){
        String s=aa.substring(0, 3) + " **** " + aa.substring(7, 11);
        return s;
    }
}
